<!--
  @author:  long
  @date:    2023/3/2
  @file:    联系人列表
  @require:
-->
<template>
  <div class="contactsList app-container">
    <!-- 联系人列表主体 start -->
    <div class="px-2">
      <!-- 搜索 start -->
      <avue-form
        :option="queryFormOption"
        v-model="queryForm"
        ref="queryFormRef"
      >
        <!--   联系人生日   -->
        <template #birthdayType>
          <el-select
            clearable
            v-model="queryForm.birthdayType"
            placeholder="联系人生日"
            @change="birthdayChange"
          >
            <el-option
              v-for="(dict, index) in birthdayOptions"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <!--   联系人角色   -->
        <template #roleCode>
          <el-select
            clearable
            v-model="queryForm.roleCode"
            placeholder="联系人角色"
          >
            <el-option
              v-for="(dict, index) in contacts_role"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <!-- 联系人星级 -->
        <template #starRating>
          <el-select
            clearable
            v-model="queryForm.starRating"
            placeholder="信用星级"
          >
            <el-option
              v-for="(dict, index) in customer_star"
              :label="dict.label"
              :value="dict.value"
              :key="index"
            ></el-option>
          </el-select>
        </template>
        <template #menu-form="{}">
          <el-button icon="Search" type="primary" @click="handleSubmit"
            >查询</el-button
          >
          <el-button icon="RefreshLeft" @click="handleEmpty">重置</el-button>
          <el-button icon="Filter" link type="primary" @click="openDrawer"
            >高级筛选</el-button
          >
        </template>
      </avue-form>
      <!-- 搜索 end -->

      <!-- 操作按钮 start-->
      <div class="px-2 pb-3">
        <el-button type="primary" icon="Plus" @click="addContacts">
          新建个人客户
        </el-button>
        <el-button icon="Flag" type="primary" @click="addTask" plain
          >新建任务</el-button
        >
        <el-button icon="List" type="primary" plain>新建工单</el-button>
        <el-button icon="Download" type="primary" plain>导入数据</el-button>
        <el-button icon="Upload" type="primary" plain>导出数据</el-button>
        <el-button icon="EditPen" type="primary" @click="toUpdate" plain
          >编辑联系人</el-button
        >
        <el-button icon="Delete" type="primary" @click="deleteContacts" plain
          >删除联系人</el-button
        >
      </div>
      <!-- 操作按钮 end-->

      <!--   联系人列表显示start   -->
      <el-table
        ref="tableRef"
        :data="tableData"
        style="width: 100%"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange"
        @row-dblclick="goDetails"
      >
        <el-table-column
          type="selection"
          align="center"
          width="55"
          :selectable="selectable"
        />
        <el-table-column
          label="姓名"
          show-overflow-tooltip
          prop="contactName"
          align="center"
        >
          <!-- <template #default="scope">
            <el-button link type="primary" @click="goDetails(scope.row)">{{
              scope.row.contactName
            }}</el-button>
          </template> -->
        </el-table-column>
        <el-table-column
          label="手机号"
          prop="contactNumber"
          align="center"
        ></el-table-column>
        <el-table-column label="关联企业" show-overflow-tooltip prop="entName">
          <!-- <template #default="scope">
            <el-button
              link
              type="primary"
              @click="goCustomerDetails(scope.row)"
              >{{ scope.row.entName }}</el-button
            >
          </template> -->
        </el-table-column>

        <!--        <el-table-column-->
        <!--          header-align="center"-->
        <!--          align="center"-->
        <!--          prop="isChiefly"-->
        <!--          label="首要联系人"-->
        <!--        >-->
        <!--          <template #default="scope">-->
        <!--            <el-button-->
        <!--              link-->
        <!--              :type="scope.row.isChiefly == '1' ? 'primary' : 'info'"-->
        <!--            >-->
        <!--              {{ scope.row.isChiefly == '1' ? '是' : '否' }}-->
        <!--            </el-button>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="信用星级" align="center">
          <template #default="scope">
            <el-rate disabled v-model="scope.row.starRating" />
          </template>
        </el-table-column>
        <el-table-column label="角色" prop="roleCode" align="center">
        </el-table-column>
        <el-table-column
          label="部门职务"
          width="100"
          prop="dutyCode"
          align="center"
        ></el-table-column>
        <el-table-column
          label="生日"
          prop="birthday"
          align="center"
          width="130"
          :formatter="dateFormat"
        ></el-table-column>
        <el-table-column
          label="最后跟进时间"
          prop="statusUpdateTime"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="170">
          <template #default="scope">
            <el-button
              icon="DocumentChecked"
              size="small"
              type="primary"
              plain
              @click="toOrder(scope.row)"
              >下订</el-button
            >
            <el-button
              icon="CircleCheck"
              type="warning"
              size="small"
              plain
              @click="clickFn(scope.row)"
              >跟进</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"
      />
      <!--   联系人列表显示end   -->

      <!-- 高级筛选 start -->
      <el-drawer class="p-0" size="50%" v-model="drawer" title="高级筛选">
        <avue-form
          :option="drawerFormOption"
          v-model="queryForm"
          ref="drawerQueryForm"
        >
          <template #menu-form="{}">
            <el-button icon="Search" type="primary" @click="handleSubmit"
              >查询</el-button
            >
            <el-button icon="RefreshLeft" @click="handleDrawerEmpty"
              >重置</el-button
            >
          </template>
          <!--   联系人状态   -->
          <template #status>
            <el-select
              v-model="queryForm.status"
              placeholder="状态"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_status"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!-- 行业类型 -->
          <template #industryTypeCode>
            <el-select
              v-model="queryForm.industryTypeCode"
              placeholder="行业类别"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in industry_category"
                :key="index"
                :value="dict.value"
                :label="dict.label"
              ></el-option>
            </el-select>
          </template>
          <!-- 联系人类别 -->
          <template #contactType>
            <el-select
              v-model="queryForm.contactType"
              placeholder="类别"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in contacts_class"
                :key="index"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </template>
          <!-- 信用星级 -->
          <template #starRating>
            <el-select
              v-model="queryForm.starRating"
              placeholder="信用星级"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_star"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!-- 联系人来源 -->
          <template #origin>
            <el-select
              v-model="queryForm.origin"
              placeholder="来源"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(dict, index) in customer_source"
                :label="dict.label"
                :value="dict.value"
                :key="index"
              ></el-option>
            </el-select>
          </template>
          <!-- 归属公司 -->
          <template #orgId>
            <el-tree-select
              style="width: 100%"
              v-model="queryForm.orgId"
              :data="companyOptions"
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              placeholder="请选择归属公司"
              value-key="id"
              filterable
              clearable
            />
          </template>
          <!--    归属人员    -->
          <template #userId>
            <el-select
              v-model="queryForm.userId"
              placeholder="请选择归属人员"
              @focus="userInputFocus"
              class="w-full"
              clearable
            >
              <el-option
                v-for="(item, index) in selectOptionObj['userId']"
                :key="index"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </template>
          <!--    所属企业    -->
          <template #entId>
            <el-select
              v-model="queryForm.entId"
              placeholder="请选择所属企业"
              class="w-full"
              filterable
              clearable
              remote
              :remote-method="queryCustomer"
            >
              <el-option
                v-for="item in parentOptions"
                :key="item.id"
                :label="item.customerName"
                :value="item.id"
              >
                <div>
                  <span>{{ item.customerName }}</span>
                  <span>({{ item.mainContactName }})</span>
                </div>
              </el-option>
            </el-select>
          </template>
        </avue-form>
      </el-drawer>
      <!-- 高级筛选 end -->
    </div>
    <!-- 联系人列表主体end -->
    <!--  公共弹窗start -->
    <el-dialog
      v-model="dialogObj.visible"
      destroy-on-close
      :close-on-click-modal="false"
      :width="dialogObj.width"
      :title="dialogObj.title"
    >
      <!--      新建任务-->

      <!--   底部按钮   -->
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary">保存</el-button>
      </template>
    </el-dialog>
    <!--  公共弹窗end -->
    <!--  弹窗选择组件  -->
    <SelectDialog :dialog-param="dialogParam" @ok="selectData"></SelectDialog>
    <!-- 跟进 -->
    <FollowUp :dialogParam="followUpParam" @close="closeFn"></FollowUp>
    <!--   新建任务   -->
    <TaskFrom :dialogParam="taskParam" @closeDialog="closeTask"></TaskFrom>
  </div>
</template>

<script setup name="ContactsList">
import { getCurrentInstance, toRaw } from 'vue'

import { useRouter } from 'vue-router'
import SelectDialog from '@/components/SelectDialog/index.vue'
import FollowUp from '@/businessComponents/FollowUp'

import {
  format,
  addDays,
  addWeeks,
  startOfMonth,
  endOfMonth,
  addMonths
} from 'date-fns'

import useCommonStore from '@/store/modules/common'
import { delContact, getContactList } from '@/api/customerManage/contactList'
import { getCustomerList } from '@/api/customerManage/customerList'
import { getMondayDate } from '@/utils/date'
import useUserStore from '@/store/modules/user'
import TaskFrom from '@/views/rsgl/taskManage/modules/add.vue'
const userStore = useUserStore()
const router = useRouter()
// 通用数据store
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const drawer = ref(false) //抽屉弹窗
const loading = ref(false)
const {
  customer_status,
  contacts_class,
  customer_source,
  customer_star,
  industry_category,
  contacts_role,
  post_dict
} = proxy.useDict(
  'customer_status',
  'contacts_class',
  'customer_source',
  'customer_star',
  'industry_category',
  'contacts_role',
  'post_dict'
)
const data = reactive({
  birthdayOptions: [
    { label: '全部', value: '1' },
    { label: '今天', value: '2' },
    { label: '明天', value: '3' },
    { label: '本周', value: '4' },
    { label: '下周', value: '5' },
    { label: '本月', value: '6' },
    { label: '下月', value: '7' }
  ],
  queryForm: {
    pageNum: 1,
    pageSize: 10,
    orgId: userStore.user.orgId,
    entType: '1' //联系人企业类型写死 客户：1 供应商：2
  },
  total: 0,
  tableData: [],
  // 查询的form表单配置
  queryFormOption: {
    labelWidth: 0,
    menuSpan: 6,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        prop: 'phoneAndNameContact',
        placeholder: '姓名或联系人电话',
        span: 4
      },
      {
        prop: 'birthdayType', //生日
        span: 3
      },
      {
        prop: 'roleCode', //联系人角色
        span: 3
      },
      {
        prop: 'starRating', //星级
        span: 3
      },
      {
        prop: 'statusUpdateTime',
        placeholder: '跟进时间',
        span: 5,
        type: 'daterange',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        startPlaceholder: '跟进日期起',
        endPlaceholder: '跟进日期止'
      }
    ]
  },
  //   高级筛选弹窗form表单配置
  drawerFormOption: {
    labelWidth: 80,
    submitBtn: false,
    emptyBtn: false,
    column: [
      {
        label: '联系人',
        prop: 'phoneAndNameContact',
        placeholder: '联系人姓名、电话',
        span: 12
      },
      {
        label: '状态',
        prop: 'status',
        span: 12
      },

      {
        label: '类别',
        prop: 'contactType',
        placeholder: '类别',
        span: 12
      },
      {
        label: '行业类型',
        prop: 'industryTypeCode',
        placeholder: '行业类型',
        span: 12
      },
      {
        label: '来源',
        prop: 'origin',
        placeholder: '来源',
        span: 12
      },
      {
        label: '信用星级',
        prop: 'starRating',
        placeholder: '信用星级',
        span: 12
      },
      {
        label: '所属企业',
        prop: 'entId',
        placeholder: '所属企业',
        span: 12
      },
      {
        label: '归属公司',
        prop: 'orgId',
        placeholder: '归属公司',
        span: 12,
        display: userStore.user.orgId == '484'
      },

      {
        label: '归属人员',
        prop: 'userId',
        placeholder: '归属人员',
        span: 12
      },
      {
        label: '职务类型',
        span: 12,
        prop: 'dutyCode',
        placeholder: '职务类型',
        type: 'select',
        dicData: post_dict
      }
    ]
  },
  dialogObj: {
    visible: false,
    title: '',
    width: '50%',
    model: '',
    type: {
      task: { title: '新建任务', width: '40%' }
    }
  },
  dialogParam: {}, //弹窗组件配置
  selectOptionObj: {}, // select
  selectionData: [],
  followUpParam: {} //跟进
})

const {
  queryForm,
  tableData,
  queryFormOption,
  drawerFormOption,
  dialogObj,
  birthdayOptions,
  dialogParam,
  selectOptionObj,
  total,
  selectionData,
  followUpParam
} = toRefs(data)

// 归属公司数据
const companyOptions = ref([])
const parentOptions = ref([])
const taskParam = ref({})

// 新建任务
const addTask = () => {
  //   taskParam.value.isVisible = true
  //   taskParam.value.businessType = '5'
  let object = {
    businessType: '5'
  }
  router.push({
    path: '/rsgl/other/addTasking',
    query: { taskParam: JSON.stringify(object) }
  })
}
// 任务关闭
const closeTask = () => {
  taskParam.value.isVisible = false
}

const dateFormat = (row, column) => {
  let date = row[column.property]
  console.info('date', column)
  if (date === undefined || date == null) {
    return ''
  }
  return date.substring(0, 10)
}

// 组件关闭隐藏
const closeFn = row => {
  // 跟进
  followUpParam.value.isVisible = false
  getList()
}

/**
 * 跟进
 * @param row
 */
const clickFn = row => {
  // 跟进
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'biz_contact'
  followUpParam.value.businessId = row.id
  followUpParam.value.linkName = row.contactName //'联系人名称'
}

/**
 * 下订
 * @param row
 */
const toOrder = row => {
  let obj = {
    customerId: row.id,
    customerName: row.contactName,
    customerType: 'cusLink'
  }
  router.push({
    path: '/sales/indent/salesOrderForm',
    query: { salesOrderData: JSON.stringify(obj) }
  })
}

//如果是首要联系人 复选框禁用
function selectable(row, rowIndex) {
  //索引是从0开始，条件1是指只有第2行数据不被禁用
  if (row.isChiefly == '1') {
    return false //不禁用
  } else {
    return true //禁用
  }
}

/**
 * 删除联系人
 */
function deleteContacts() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除选中的联系人数据？')
    .then(res => {
      let ids = selectionData.value
        .map(item => {
          return item.id
        })
        .join(',')
      console.info('ids', ids)
      const params = {
        ids
      }
      delContact(params).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        getList()
      })
    })
    .catch(() => {})
}

/**
 * 跳转联系人详情
 * @param row 行数据
 */
function goDetails(row) {
  router.push({
    path: '/customerManage/contactsModules/contactsDetails',
    query: { contactsId: row.id }
  })
}

/**
 * 跳转客户详情
 * @param row
 */
function goCustomerDetails(row) {
  router.push({
    path: '/customerManage/customerModules/customerDetails',
    query: { customerId: row.entId }
  })
}

/**
 * 生日选择 根据选择获取生日范围
 */
function birthdayChange(val) {
  switch (val) {
    case '2': //今天
      queryForm.value.birthdayStart = format(new Date(), 'yyyy-MM-dd 00:00:00')
      queryForm.value.birthdayEnd = format(new Date(), 'yyyy-MM-dd 23:59:59')
      break

    case '3': //明天
      queryForm.value.birthdayStart = format(
        addDays(new Date(), 1),
        'yyyy-MM-dd 00:00:00'
      )
      queryForm.value.birthdayEnd = format(
        addDays(new Date(), 1),
        'yyyy-MM-dd 23:59:59'
      )
      break
    case '4': //本周
      queryForm.value.birthdayStart = getMondayDate(new Date()).monStartday
      queryForm.value.birthdayEnd = getMondayDate(new Date()).monEndDay

      break
    case '5': //下周
      //addWeeks 当前日期加一周
      queryForm.value.birthdayStart = getMondayDate(
        addWeeks(new Date(), 1)
      ).monStartday
      queryForm.value.birthdayEnd = getMondayDate(
        addWeeks(new Date(), 1)
      ).monEndDay
      break
    case '6': //本月
      queryForm.value.birthdayStart = format(
        startOfMonth(new Date()),
        'yyyy-MM-dd 00:00:00'
      )
      queryForm.value.birthdayEnd = format(
        endOfMonth(new Date()),
        'yyyy-MM-dd 23:59:59'
      )
      break
    case '7': //下月
      //addMonths 当前月份加一个月
      queryForm.value.birthdayStart = format(
        startOfMonth(addMonths(new Date(), 1)),
        'yyyy-MM-dd 00:00:00'
      )
      queryForm.value.birthdayEnd = format(
        endOfMonth(addMonths(new Date(), 1)),
        'yyyy-MM-dd 23:59:59'
      )
      break
  }
  console.info('queryForm.value', queryForm.value)
}

/**
 * 所属企业模糊搜索
 * @param val 当前输入的值
 */
function queryCustomer(val) {
  let params = {
    pageNum: 1,
    pageSize: 10,
    customerNameOrNumber: val
  }
  getCustomerList(params).then(res => {
    parentOptions.value = res.data.records
  })
}

/**
 * 弹窗选取获取选中的值
 * @param val
 *  type 业务类型
 *     selectData 选中的数据[{value: 1, label: '王晓易', $treeNodeId: 2}]
 *     labelData 选中的数据label ['王晓易']
 *     defaultCheckedKeys 选中的数据id [1]
 *     dialogVisible: false 弹出框的关闭
 */
function selectData(val) {
  console.info('val', val)
  //归属人员
  if (val.type == 'userId') {
    if (!val.selectData.length) {
      queryForm.value[val.type] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      queryForm.value[val.type] = val.defaultCheckedKeys[0]
    }
  }
}

/**
 * 获取联系人数据
 */
function getList() {
  loading.value = true
  // console.info('userStore', statusUpdateTime.value)
  let params = JSON.parse(JSON.stringify(queryForm.value))
  if (params.statusUpdateTime != null && params.statusUpdateTime.length > 0) {
    params.statusUpdateTimeStart = params.statusUpdateTime[0] + ' 00:00:00'
    params.statusUpdateTimeEnd = params.statusUpdateTime[1] + ' 23:59:59'
  } else {
    params.statusUpdateTimeStart = undefined
    params.statusUpdateTimeEnd = undefined
  }
  delete params.statusUpdateTime
  delete params.birthdayType
  if (userStore.user.orgId != 484) {
    params.orgId = userStore.user.orgId
  }

  getContactList(params)
    .then(res => {
      if (res.data != null) {
        tableData.value = res.data.records
        total.value = res.data.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(res => {
      loading.value = false
    })
}

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  dialogParam.value.type = 'userId'
  dialogParam.value.title = '选择归属人员'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'id'

  selectOptionObj.value['userId'] = []
  if (queryForm.value['userId'] && queryForm.value['userId'].length) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [queryForm.value['userId']]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 弹窗关闭
 */
function handleCloseDialog() {
  dialogObj.value.visible = false
}

/**
 * 弹窗开启操作
 * @param type 弹窗组件类型
 *
 */
function handleOpenDialog(type) {
  dialogObj.value.title = dialogObj.value.type[type].title
  dialogObj.value.width = dialogObj.value.type[type].width
  dialogObj.value.model = type
  dialogObj.value.visible = true
}

/**
 * 表格多选
 */
function handleSelectionChange(val) {
  selectionData.value = val
}

/**
 * 新建联系人
 */
function addContacts() {
  router.push({
    path: '/customerManage/contactsModules/contactsAdd',
    query: { flag: 'add' }
  })
}

/**
 * 联系人编辑
 */
function toUpdate() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要编辑的数据')
    return
  }
  if (selectionData.value.length > 1) {
    proxy.$modal.msgWarning('只能编辑一条数据')
    return
  }
  router.push({
    path: '/customerManage/contactsModules/contactsEdit',
    query: { flag: 'update', contactsId: selectionData.value[0].id }
  })
}

/**
 * 初始化
 */
function init() {
  //   获取所属公司数据
  commonStore.getCompanyData().then(data => {
    companyOptions.value = data
    if (userStore.user.orgId !== '484') {
      queryForm.value.orgId = userStore.user.orgId * 1
    }
  })
  getList()
}
init()

/**
 * 打开高级筛选抽屉
 */
function openDrawer() {
  drawer.value = true
}

/**
 * 查询
 */
function handleSubmit() {
  queryForm.value.pageNum = 1
  getList()
}

/**
 * 重置
 */
async function handleEmpty() {
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    entType: '1', //联系人企业类型写死 客户：1 供应商：2
    birthdayEnd: undefined,
    birthdayStart: undefined
  }
  proxy.$refs.queryFormRef.resetFields()
  await getList()
}
/**
 * 高级筛选重置
 */
async function handleDrawerEmpty() {
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    entType: '1', //联系人企业类型写死 客户：1 供应商：2
    birthdayEnd: undefined,
    birthdayStart: undefined
  }
  proxy.$refs.drawerQueryForm.resetFields()

  await getList()
}
</script>

<style scoped lang="scss">
.customerList {
  .el-drawer .avue-form {
    @apply p-0;
  }
}
</style>
